package com.csc.usermanagement.admin;

import java.io.IOException;
import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.csc.usermanagement.dao.UserManagementDbConnector;
import com.csc.usermanagement.model.User;

/**
 * Servlet implementation class ListAllUsers
 */
@WebServlet("/ListAllUsers")
public class ListAllUsers extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public ListAllUsers() {
		super();
		// TODO Auto-generated constructor stub
	}
	
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		Connection conn = null;
		PreparedStatement stmt = null;
		ResultSet rs = null;

		String sql = "select * from user";
		try {
			conn = UserManagementDbConnector.getConnection();
			stmt = conn.prepareStatement(sql);
			rs = stmt.executeQuery();
			ArrayList<User> users = new ArrayList<User>();
			while (rs.next()) {
				String username = rs.getString("UserName");
				String password = rs.getString("Password");
				String type = rs.getString("Type");
				Date registeredDate = rs.getDate("RegisteredDate");
				User user = new User(username, password, type, registeredDate);
				users.add(user);
			}
			request.setAttribute("users", users);
			request.getRequestDispatcher("AdminAllUsers.jsp").forward(request, response);
		} catch (SQLException se) {
			se.printStackTrace();
		}

	}

}
